"""Centralized CORS configuration helper."""
from __future__ import annotations

import os
from typing import Iterable, List, Set

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from backend.common.config import config_manager


def _collect_default_origins() -> Set[str]:
    return {
        "http://127.0.0.1:5173",
        "http://localhost:5173",
        "http://127.0.0.1:8001",
        "http://localhost:8001",
    }


def _parse_env_origins() -> Set[str]:
    """
    Support FRONTEND_URL or FRONTEND_ORIGINS env vars (comma separated).
    """
    origins: Set[str] = set()
    single = os.getenv("FRONTEND_URL")
    if single:
        origins.add(single.rstrip("/"))

    joined = os.getenv("FRONTEND_ORIGINS")
    if joined:
        for item in joined.split(","):
            value = item.strip()
            if value:
                origins.add(value.rstrip("/"))
    return origins


def _normalize(origins: Iterable[str]) -> List[str]:
    normalized = []
    for origin in origins:
        trimmed = origin.strip().rstrip("/")
        if trimmed:
            normalized.append(trimmed)
    return normalized


def configure_cors(app: FastAPI) -> None:
    """
    Apply a consistent CORSMiddleware configuration to the provided app.
    """
    configured = config_manager.api.cors_origins
    configured_set: Set[str]
    if isinstance(configured, str):
        configured_set = {configured}
    else:
        configured_set = set(configured or [])

    default = _collect_default_origins()
    env_origins = _parse_env_origins()

    combined = default.union(env_origins).union(configured_set)
    if not combined or "*" in combined:
        allow_origins = ["*"]
    else:
        allow_origins = _normalize(combined)

    app.add_middleware(
        CORSMiddleware,
        allow_origins=allow_origins,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
        expose_headers=["*"],
        max_age=600,
    )

